// author diqye email 262666212@qq.com
mod(['//cdn.bootcss.com/markdown-it/8.3.1/markdown-it.min.js'],function(script){
  var STATE_RENDERED = [] //当ppt页渲染之后
  var md = markdownit()

  function keyup(fn){
    document.addEventListener('keyup',fn)
  }
  function whenTouch(option){
    var start = null
    document.addEventListener('touchstart',function(e){
      start = e.changedTouches[0]
    })
    document.addEventListener('touchend',function(e){
      var end = e.changedTouches[0]
      if(start.screenX - end.screenX < -50){
        option.prev()
      }else if(start.screenX - end.screenX > 50){
        option.next()
      }
    })
  }

  function whenKey(option){
    keyup(function(e){
      if(e.key == ' '){
        option.next()
      }else if(e.key == 'n'&&e.ctrlKey){
        option.next()
      }else if(e.key == 'ArrowDown'){
        option.next()
      }else if(e.key == 'ArrowUp'){
        option.prev()
      }else if(e.key == 'p'&&e.ctrlKey){
        option.prev()
      }else if(e.key == 'Alt'){
        option.prev()
      }else{
        void null
      }
    })
    whenTouch(option)
  }

  function filter(fn,xs){
    var r = []
    for(var i=0;i<xs.length;i++){
      if(fn(xs[i])){
        r.push(xs[i])
      }else{
        void null
      }
    }
    return r
  }

  function tail(xs){
    return xs.slice(1)
  }
  function head(xs){
    return xs[0]
  }

  function startWith(a,str){
    if(str.trim().slice(0,a.length) == a){
      return true
    }else{
      return false
    }
  }
  function conj(a,xs){
    return [a].concat(xs)
  }

  function parse(str){
    function p(lines){
      if(lines.length == 0){
        return []
      }else{
        var a = tokenP(lines,'')
        if(a.type == 'normal-next'){
          var next = a.tData
          var b = conj({
            type:'multiple', 
            data:next.item ,
            header:next.header
          },p(next.tail))
          if(a.item.length == 0){
            return b
          }else{
            return conj({type:'normal', data:a.item },b)
          }
        }else if(a.item.length == 0){
          return p(a.tail)
        }else {
          return conj({
            type:'normal',
            data:a.item
          },p(a.tail))
        }
      }
    }
    function tokenP(lines, end){
      if(lines.length == 0){
        return {
          item:[],
          type:'normal',
          tail:[]
        }
      }else{
        var h = lines[0]
        var t = lines.slice(1)
        if(h.trim() == end){
          return {
            item:[],
            type:'normal',
            tail:t
          }
        }else if(startWith(':start',h)){
          var item = tokenP(lines.slice(1),':end')
          return {
            tail:item.tail,
            item:[],
            type:'normal-next',
            tData:{
              item: item.item,
              tail:item.tail,
              type:item.type,
              header:filter(function(a){ return a != ""},h.trim().slice(6).split(' ')),
              tData:item.tData
            }
          }
        }else{
          var item = tokenP(lines.slice(1), end)
          return {
            item:conj(h,item.item),
            tail:item.tail,
            type:item.type,
            tData:item.tData
          }
        }
      }
      
    }
    return p(str.split('\n'))
  }
  function doItem(fn,itemfn,sharObj){
    var hash = window.location.hash
    var idx = 0
    if(hash == ""){
      void null
    }else{
      idx = parseInt(hash.slice(1)) - 1
      idx = idx < 0              ? 0 
      : idx > sharObj.length - 1 ? sharObj.length -1 
      : idx
    }
    var citem = sharObj[idx]
    whenKey({
      prev:function(){
        if(idx <= 0){
          alert('已经到头部了')
        }else{
          idx --
          citem = sharObj[idx]
          _view()
        }
      },
      next:function(){
        if(idx >= sharObj.length-1){
          alert('已经到尾部了')
        }else{
          if(citem.hasNext&&citem.hasNext()){
            citem.nextfn()
          }else{
            idx ++
            citem = sharObj[idx]
            _view()
          }
        }
      }
    })
    function _view(){
      fn(itemfn(citem))
      window.location.hash = idx + 1
      each(STATE_RENDERED,function(fn){
        fn(idx,sharObj)
      })
    }
    _view()
  }

  function handlerItem(item){
    if(item.type == 'normal'){
      return donormal(item.data)
    }else if(item.type == 'multiple'){
      return domultiple(item.data, item.header)
    }else{
      return '找不到这种类型的数据'
    }
    function donormal(xs){
      if(isH2(xs)){
        return '<div class="jz one md">' + md.render(xs[0]) + '</div>'
      }else if(isH2P(xs)){
        return '<div class="jz two md">' + md.render(xs.join('\n')) + '</div>'
      }else{
        return '<div class="md">' + md.render(xs.join('\n')) + '</div>'
      }
    }
    function domultiple(xs,header){
      return '<div class="md '+header.join(' ')+'">' + md.render(xs.join('\n')) + '</div>'
    }
  }

  function isH2(xs){
    return xs.length == 1
  }

  function isH2P(xs){
    return xs.length == 2
  }
  function view(target){
    return function(html){
      target.innerHTML = html
    }
  }

  function topx(a){
    return a + 'px'
  }
  function remTranstion(){
    var w = window.innerWidth
    var wl = w/1000
    document.querySelector('html')['style']['font-size'] = topx(100 * wl)
    window.onresize = remTranstion
  }
  // [a] -> (a->Void) -> Void
  function each(xs,fn){
    for (var i = 0; i < xs.length; i++) {
      var x = xs[i];
      fn(x);
    }
  }
  //<script src="//cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js"></script>
  function useHighlight(theme){
    if(theme  == 'light'){
      imptcss('//cdn.bootcss.com/highlight.js/9.12.0/styles/atom-one-light.min.css')
    }else if(theme != null){
      imptcss(theme)
    }else{
      imptcss('//cdn.bootcss.com/highlight.js/9.12.0/styles/atom-one-dark.min.css')
    }
    imptjs('//cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js')
    .then(function(){
      highlight()
      STATE_RENDERED.push(function(){
        highlight()
      })
    })

    function highlight(){
      each(document.querySelectorAll('pre code'),function(block){
        hljs.highlightBlock(block)
      })
    }
  }
  function usePage(div){
    STATE_RENDERED.push(function(idx,xs){
      div.innerHTML = (idx + 1) + '/' + xs.length
    })
  }
  function mauto(theme){
    run(document.querySelector('xmp').innerHTML,document.getElementById('target'))
    useHighlight(theme)
    usePage(document.getElementById('page'))
  }
  function run(mppt,target){
    remTranstion()
    var sharObj = parse(mppt)
    doItem(view(target), handlerItem, sharObj)
  }
  return {
    mauto:mauto,
    run:run,
    useHighlight:useHighlight,
    usePage:usePage
  }
})